import { listen } from '@src/utils/listener'
import { onWindowMousedown } from '@src/events/mouse'

export function setupTouchEvent(self, option) {

  // 触摸开始
  listen(window, 'touchstart', function(ev) {
    if (ev.target.id !== 'overlays') return;
    var touches = ev.changedTouches;
    for (var i=0; i<touches.length; i++) {
      option.ongoingTouches[touches[i].identifier] = touches[i];
    }

    if (option.activeTouch === null) {
      self.touchMode = true;
      // window.onmousedown(touches[0]);
      onWindowMousedown(touches[0], self, option)
      option.activeTouch = touches[0].identifier;
    }

    ev.preventDefault();
  });

  // 触摸结束
  listen(window, 'touchend', function(ev) {
    if (ev.target.id !== 'overlays') return;
    var touches = ev.changedTouches;
    for (var i=0; i<touches.length; i++) {
      delete option.ongoingTouches[touches[i].identifier];
      if (touches[i].identifier === option.activeTouch) {
        // window.onmouseup(touches[i]);
        onWindowMouseup(touches[i], self, option)
        option.activeTouch = null;
        self.touchMode = false;
      }
    }
    ev.preventDefault();
  });

  // 取消触摸
  listen(window, 'touchcancel', function(ev) {
    if (ev.target.id !== 'overlays') return;
    var touches = ev.changedTouches;
    for (var i=0; i<touches.length; i++) {
      delete option.ongoingTouches[touches[i].identifier];
      if (touches[i].identifier === option.activeTouch) {
        // window.onmouseup(touches[i]);
        onWindowMouseup(touches[i], self, option)
        option.activeTouch = null;
        self.touchMode = false;
      }
    }
    ev.preventDefault();
  });

  // 触摸移动
  listen(window, 'touchmove', function(ev) {
    if (ev.target.id !== 'overlays') return;
    var touches = ev.changedTouches;
    for (var i=0; i<touches.length; i++) {
      delete option.ongoingTouches[touches[i].identifier];
      if (touches[i].identifier === option.activeTouch) {
        // window.onmousemove(touches[i]);
        onWindowMousemove(touches[i], self, option)
      }
    }
    ev.preventDefault();
  });
}
